package com.nirvana.resolve;

import com.nirvana.data.DefPropertyData;
import com.nirvana.type.ResolveState;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FbsResolver extends AbstractResolver {
    private ResolveState state = ResolveState.NONE;
    private final Pattern tablePattern = Pattern.compile("table\\s*(.*?Fb)\\s*\\{\\s*");
    private final Pattern propertyPattern = Pattern.compile("\\s+(.*?)\\s*:\\s*(.*?)\\s*;");
    public FbsResolver(File file) {
        super(file);
    }

    @Override
    public List<DefPropertyData> resolve() {
        try {
            List<String> lines = Files.readAllLines(Paths.get(file.toURI()));
            List<DefPropertyData> list = new ArrayList<>();
            for (String line : lines) {
                if (state == ResolveState.NONE && tablePattern.matcher(line).matches()) {
                    state = ResolveState.PROPERTY_NAME;
                } else if (state == ResolveState.PROPERTY_NAME) {
                    Matcher matcher = propertyPattern.matcher(line);
                    if (matcher.find()) {
                        String propertyName = matcher.group(1);
                        String propertyType = matcher.group(2);
                        DefPropertyData data = new DefPropertyData();
                        data.setPropertyName(propertyName);
                        data.setSourceName("");
                        data.setResolveMethod("auto");
                        data.setTypeIndex(propertyType);
                        list.add(0, data);
                    }
                }
            }

            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String getDefClassName() {
        String name = file.getName();
        return name.substring(0, name.lastIndexOf("."));
    }
}
